package com.sychip.fhc.app.ble

import com.fhc.view.NFCBleStatus
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.data.repo.BleDeviceRepo
import com.sychip.fhc.app.pref.PrefDataStoreIf
import com.sychip.fhc.base.BaseAppViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import timber.log.Timber
import javax.inject.Inject

class BleNfcViewModel @Inject constructor(
    app : MainApplication,
    private val userRepo: BleDeviceRepo,
    private val acDataStoreRepo: PrefDataStoreIf
) : BaseAppViewModel(app) {

    fun publishBleNfc(status: NFCBleStatus){
//    val a = EventDataBleNfc()
//    a.bleMac = status.bleMac
//    a.info = status.info
//    a.connectedTime = status.connectedTime
//    a.state = status.state
//    val _a = FlowEventBusData(EventType.Any, a)
//    Timber.i("publishBleNfc  >>>>>>>>>>>  state:${a.state}    info:${a.info}       bleMac:${a.bleMac}")
//    FhcFlowEventBus.publish(_a)
    }
    private val _nfcStatus = MutableStateFlow<NFCBleStatus>(NFCBleStatus())
    val nfcStatus: StateFlow<NFCBleStatus> = _nfcStatus.asStateFlow()
    fun updateBleNFCConnected(state: Int, bleMac: String? = "") {
        Timber.i("updateBleNFCConnected  >>>>>>>>>>>  $state")
        if(bleMac != null) _nfcStatus.value.bleMac=bleMac
        _nfcStatus.value.state=state
        if(state == 1){
            _nfcStatus.value.info="Try to connect..."
            _nfcStatus.value.connectedTime=0
//            _nfcStatus.update {
//                NFCBleStatus(state=state,info="Try to connect...",connectedTime = 0)
//            }
        }else if(state == -1){
            Timber.i("currentTimeMillis:        ${System.currentTimeMillis()}")
            _nfcStatus.value.info="Cannot connect."
            _nfcStatus.value.connectedTime= System.currentTimeMillis() - MainApplication.instance().startTimeMillis
//            _nfcStatus.update {
//                NFCBleStatus(state=state,info="Cannot connect.",connectedTime = System.currentTimeMillis() - MainApplication.instance().startTimeMillis)
//            }
        }else if(state == 2){
            _nfcStatus.value.info="BLE Connected."
            _nfcStatus.value.connectedTime= System.currentTimeMillis() - MainApplication.instance().startTimeMillis
//            _nfcStatus.update {
//                NFCBleStatus(state=state,info="BLE Connected.",connectedTime = System.currentTimeMillis() - MainApplication.instance().startTimeMillis)
//            }
        }else if(state == 0){
            _nfcStatus.value.info="Init..."
            _nfcStatus.value.connectedTime=-1
//            _nfcStatus.update {
//                NFCBleStatus(state=state,info="Init...",connectedTime = - 1)
//            }
        }
        publishBleNfc(_nfcStatus.value)
    }


}